package com.cencat.merchant.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cencat.common.response.ApiResponse;
import com.cencat.common.exception.BusinessException;
import com.cencat.merchant.entity.MerchantUser;
import com.cencat.merchant.service.MerchantUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.NotBlank;
import java.util.List;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

/**
 * 商家用户管理控制器
 * @author cencat
 * @since 2024-01-01
 */
@RestController
@RequestMapping("/api/merchant-user")
@Tag(name = "商家用户管理", description = "商家用户管理相关接口")
@Slf4j
@Validated
public class MerchantUserController {

    @Autowired
    private MerchantUserService merchantUserService;

    /**
     * 创建商家用户
     * @param merchantUser 商家用户信息
     * @return 用户ID
     */
    @PostMapping("/create")
    @Operation(summary = "创建商家用户", description = "创建新的商家用户")
    public ApiResponse<Long> createMerchantUser(@Valid @RequestBody MerchantUser merchantUser) {
        try {
            Long userId = merchantUserService.createMerchantUser(merchantUser);
            return ApiResponse.success(userId);
        } catch (BusinessException e) {
            log.error("创建商家用户失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("创建商家用户异常: {}", e.getMessage(), e);
            return ApiResponse.error("创建商家用户失败");
        }
    }

    /**
     * 更新商家用户信息
     * @param merchantUser 商家用户信息
     * @return 是否成功
     */
    @PutMapping("/update")
    @Operation(summary = "更新商家用户信息", description = "更新商家用户基本信息")
    public ApiResponse<Boolean> updateMerchantUser(@Valid @RequestBody MerchantUser merchantUser) {
        try {
            Boolean result = merchantUserService.updateMerchantUser(merchantUser);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("更新商家用户信息失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("更新商家用户信息异常: {}", e.getMessage(), e);
            return ApiResponse.error("更新商家用户信息失败");
        }
    }

    /**
     * 删除商家用户
     * @param userId 用户ID
     * @return 是否成功
     */
    @DeleteMapping("/delete/{userId}")
    @Operation(summary = "删除商家用户", description = "删除指定商家用户")
    public ApiResponse<Boolean> deleteMerchantUser(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotNull @Min(1) Long userId) {
        try {
            Boolean result = merchantUserService.deleteMerchantUser(userId);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("删除商家用户失败: userId={}, error={}", userId, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("删除商家用户异常: userId={}, error={}", userId, e.getMessage(), e);
            return ApiResponse.error("删除商家用户失败");
        }
    }

    /**
     * 根据ID获取商家用户信息
     * @param userId 用户ID
     * @return 用户信息
     */
    @GetMapping("/get/{userId}")
    @Operation(summary = "获取商家用户信息", description = "根据ID获取商家用户详细信息")
    public ApiResponse<MerchantUser> getMerchantUserById(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotNull @Min(1) Long userId) {
        try {
            MerchantUser merchantUser = merchantUserService.getMerchantUserById(userId);
            return ApiResponse.success(merchantUser);
        } catch (BusinessException e) {
            log.error("获取商家用户信息失败: userId={}, error={}", userId, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("获取商家用户信息异常: userId={}, error={}", userId, e.getMessage(), e);
            return ApiResponse.error("获取商家用户信息失败");
        }
    }

    /**
     * 根据用户名获取商家用户信息
     * @param username 用户名
     * @return 用户信息
     */
    @GetMapping("/getByUsername/{username}")
    @Operation(summary = "根据用户名获取用户信息", description = "根据用户名获取商家用户详细信息")
    public ApiResponse<MerchantUser> getMerchantUserByUsername(
            @Parameter(description = "用户名", required = true)
            @PathVariable String username) {
        try {
            MerchantUser merchantUser = merchantUserService.getMerchantUserByUsername(username);
            return ApiResponse.success(merchantUser);
        } catch (BusinessException e) {
            log.error("根据用户名获取用户信息失败: username={}, error={}", username, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("根据用户名获取用户信息异常: username={}, error={}", username, e.getMessage(), e);
            return ApiResponse.error("获取用户信息失败");
        }
    }

    /**
     * 根据邮箱获取商家用户信息
     * @param email 邮箱
     * @return 用户信息
     */
    @GetMapping("/getByEmail/{email}")
    @Operation(summary = "根据邮箱获取用户信息", description = "根据邮箱获取商家用户详细信息")
    public ApiResponse<MerchantUser> getMerchantUserByEmail(
            @Parameter(description = "邮箱", required = true)
            @PathVariable String email) {
        try {
            MerchantUser merchantUser = merchantUserService.getMerchantUserByEmail(email);
            return ApiResponse.success(merchantUser);
        } catch (BusinessException e) {
            log.error("根据邮箱获取用户信息失败: email={}, error={}", email, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("根据邮箱获取用户信息异常: email={}, error={}", email, e.getMessage(), e);
            return ApiResponse.error("获取用户信息失败");
        }
    }

    /**
     * 根据手机号获取商家用户信息
     * @param phone 手机号
     * @return 用户信息
     */
    @GetMapping("/getByPhone/{phone}")
    @Operation(summary = "根据手机号获取用户信息", description = "根据手机号获取商家用户详细信息")
    public ApiResponse<MerchantUser> getMerchantUserByPhone(
            @Parameter(description = "手机号", required = true)
            @PathVariable String phone) {
        try {
            MerchantUser merchantUser = merchantUserService.getMerchantUserByPhone(phone);
            return ApiResponse.success(merchantUser);
        } catch (BusinessException e) {
            log.error("根据手机号获取用户信息失败: phone={}, error={}", phone, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("根据手机号获取用户信息异常: phone={}, error={}", phone, e.getMessage(), e);
            return ApiResponse.error("获取用户信息失败");
        }
    }

    /**
     * 根据商家ID获取用户列表
     * @param merchantId 商家ID
     * @return 用户列表
     */
    @GetMapping("/listByMerchant/{merchantId}")
    @Operation(summary = "获取商家用户列表", description = "根据商家ID获取用户列表")
    public ApiResponse<List<MerchantUser>> getMerchantUsersByMerchantId(
            @Parameter(description = "商家ID", required = true)
            @PathVariable @NotNull @Min(1) Long merchantId) {
        try {
            List<MerchantUser> users = merchantUserService.getMerchantUsersByMerchantId(merchantId);
            return ApiResponse.success(users);
        } catch (BusinessException e) {
            log.error("获取商家用户列表失败: merchantId={}, error={}", merchantId, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("获取商家用户列表异常: merchantId={}, error={}", merchantId, e.getMessage(), e);
            return ApiResponse.error("获取用户列表失败");
        }
    }

    /**
     * 分页查询商家用户列表
     * @param current 当前页
     * @param size 页大小
     * @param tenantId 租户ID
     * @param merchantId 商家ID
     * @param username 用户名
     * @param realName 真实姓名
     * @param phone 手机号
     * @param status 状态
     * @return 分页结果
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询商家用户", description = "分页查询商家用户列表")
    public ApiResponse<IPage<MerchantUser>> getMerchantUsersPage(
            @Parameter(description = "当前页", required = true)
            @RequestParam @Min(1) int current,
            @Parameter(description = "页大小", required = true)
            @RequestParam @Min(1) int size,
            @Parameter(description = "租户ID", required = true)
            @RequestParam @NotNull Long tenantId,
            @Parameter(description = "商家ID")
            @RequestParam(required = false) Long merchantId,
            @Parameter(description = "用户名")
            @RequestParam(required = false) String username,
            @Parameter(description = "真实姓名")
            @RequestParam(required = false) String realName,
            @Parameter(description = "手机号")
            @RequestParam(required = false) String phone,
            @Parameter(description = "状态")
            @RequestParam(required = false) String status) {
        try {
            Page<MerchantUser> page = new Page<>(current, size);
            IPage<MerchantUser> result = merchantUserService.getMerchantUserPage(page, tenantId, merchantId, username, realName, phone, status);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("分页查询商家用户失败: error={}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("分页查询商家用户异常: error={}", e.getMessage(), e);
            return ApiResponse.error("查询用户列表失败");
        }
    }

    /**
     * 用户登录
     * @param username 用户名
     * @param password 密码
     * @return 登录用户信息
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "商家用户登录验证")
    public ApiResponse<MerchantUser> login(
            @Parameter(description = "用户名", required = true)
            @RequestParam @NotBlank String username,
            @Parameter(description = "密码", required = true)
            @RequestParam @NotBlank String password) {
        try {
            MerchantUser user = merchantUserService.login(username, password);
            return ApiResponse.success(user);
        } catch (BusinessException e) {
            log.error("用户登录失败: username={}, error={}", username, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("用户登录异常: username={}, error={}", username, e.getMessage(), e);
            return ApiResponse.error("登录失败");
        }
    }

    /**
     * 修改密码
     * @param userId 用户ID
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @return 是否成功
     */
    @PutMapping("/changePassword/{userId}")
    @Operation(summary = "修改密码", description = "用户修改密码")
    public ApiResponse<Boolean> changePassword(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotNull @Min(1) Long userId,
            @Parameter(description = "旧密码", required = true)
            @RequestParam @NotBlank String oldPassword,
            @Parameter(description = "新密码", required = true)
            @RequestParam @NotBlank String newPassword) {
        try {
            Boolean result = merchantUserService.changePassword(userId, oldPassword, newPassword);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("修改密码失败: userId={}, error={}", userId, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("修改密码异常: userId={}, error={}", userId, e.getMessage(), e);
            return ApiResponse.error("修改密码失败");
        }
    }

    /**
     * 重置密码
     * @param userId 用户ID
     * @param newPassword 新密码
     * @return 是否成功
     */
    @PutMapping("/resetPassword/{userId}")
    @Operation(summary = "重置密码", description = "管理员重置用户密码")
    public ApiResponse<Boolean> resetPassword(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotNull @Min(1) Long userId,
            @Parameter(description = "新密码", required = true)
            @RequestParam @NotBlank String newPassword) {
        try {
            Boolean result = merchantUserService.resetPassword(userId, newPassword);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("重置密码失败: userId={}, error={}", userId, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("重置密码异常: userId={}, error={}", userId, e.getMessage(), e);
            return ApiResponse.error("重置密码失败");
        }
    }

    /**
     * 启用用户
     * @param userId 用户ID
     * @return 是否成功
     */
    @PutMapping("/enable/{userId}")
    @Operation(summary = "启用用户", description = "启用指定用户")
    public ApiResponse<Boolean> enableUser(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotNull @Min(1) Long userId) {
        try {
            Boolean result = merchantUserService.enableUser(userId);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("启用用户失败: userId={}, error={}", userId, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("启用用户异常: userId={}, error={}", userId, e.getMessage(), e);
            return ApiResponse.error("启用用户失败");
        }
    }

    /**
     * 禁用用户
     * @param userId 用户ID
     * @return 是否成功
     */
    @PutMapping("/disable/{userId}")
    @Operation(summary = "禁用用户", description = "禁用指定用户")
    public ApiResponse<Boolean> disableUser(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotNull @Min(1) Long userId) {
        try {
            Boolean result = merchantUserService.disableUser(userId);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("禁用用户失败: userId={}, error={}", userId, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("禁用用户异常: userId={}, error={}", userId, e.getMessage(), e);
            return ApiResponse.error("禁用用户失败");
        }
    }

    /**
     * 设置用户角色
     * @param userId 用户ID
     * @param roleIds 角色ID列表
     * @return 设置结果
     */
    @PutMapping("/setRoles/{userId}")
    @Operation(summary = "设置用户角色", description = "设置用户角色")
    public ApiResponse<Boolean> setUserRoles(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotNull @Min(1) Long userId,
            @Parameter(description = "角色ID列表", required = true)
            @RequestBody @NotNull List<Long> roleIds) {
        try {
            Boolean result = merchantUserService.setUserRoles(userId, roleIds);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("设置用户角色失败: userId={}, roleIds={}, error={}", userId, roleIds, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("设置用户角色异常: userId={}, roleIds={}, error={}", userId, roleIds, e.getMessage(), e);
            return ApiResponse.error("设置用户角色失败");
        }
    }

    /**
     * 设置用户权限
     * @param userId 用户ID
     * @param permissions 权限列表
     * @return 设置结果
     */
    @PutMapping("/setPermissions/{userId}")
    @Operation(summary = "设置用户权限", description = "设置用户权限")
    public ApiResponse<Boolean> setUserPermissions(
            @Parameter(description = "用户ID", required = true)
            @PathVariable @NotNull @Min(1) Long userId,
            @Parameter(description = "权限列表", required = true)
            @RequestBody @NotNull List<String> permissions) {
        try {
            Boolean result = merchantUserService.setUserPermissions(userId, permissions);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("设置用户权限失败: userId={}, permissions={}, error={}", userId, permissions, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("设置用户权限异常: userId={}, permissions={}, error={}", userId, permissions, e.getMessage(), e);
            return ApiResponse.error("设置用户权限失败");
        }
    }

    /**
     * 统计用户数量
     * @param merchantId 商家ID
     * @return 用户数量
     */
    @GetMapping("/count")
    @Operation(summary = "统计用户数量", description = "统计商家用户数量")
    public ApiResponse<Long> countMerchantUsers(
            @Parameter(description = "商家ID", required = true)
            @RequestParam @NotNull Long merchantId) {
        try {
            Long count = merchantUserService.countUsersByMerchantId(merchantId);
            return ApiResponse.success(count);
        } catch (BusinessException e) {
            log.error("统计用户数量失败: merchantId={}, error={}", merchantId, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("统计用户数量异常: merchantId={}, error={}", merchantId, e.getMessage(), e);
            return ApiResponse.error("统计用户数量失败");
        }
    }

    /**
     * 检查用户名是否存在
     * @param username 用户名
     * @param excludeId 排除的用户ID（可选）
     * @return 是否存在
     */
    @GetMapping("/checkUsername/{username}")
    @Operation(summary = "检查用户名是否存在", description = "检查用户名是否已被使用")
    public ApiResponse<Boolean> checkUsernameExists(
            @Parameter(description = "用户名", required = true)
            @PathVariable String username,
            @Parameter(description = "排除的用户ID")
            @RequestParam(required = false) Long excludeId) {
        try {
            Boolean exists = merchantUserService.checkUsernameExists(username, excludeId);
            return ApiResponse.success(exists);
        } catch (BusinessException e) {
            log.error("检查用户名失败: username={}, error={}", username, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("检查用户名异常: username={}, error={}", username, e.getMessage(), e);
            return ApiResponse.error("检查用户名失败");
        }
    }

    /**
     * 检查邮箱是否存在
     * @param email 邮箱
     * @param excludeId 排除的用户ID（可选）
     * @return 是否存在
     */
    @GetMapping("/checkEmail/{email}")
    @Operation(summary = "检查邮箱是否存在", description = "检查邮箱是否已被使用")
    public ApiResponse<Boolean> checkEmailExists(
            @Parameter(description = "邮箱", required = true)
            @PathVariable String email,
            @Parameter(description = "排除的用户ID")
            @RequestParam(required = false) Long excludeId) {
        try {
            Boolean exists = merchantUserService.checkEmailExists(email, excludeId);
            return ApiResponse.success(exists);
        } catch (BusinessException e) {
            log.error("检查邮箱失败: email={}, error={}", email, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("检查邮箱异常: email={}, error={}", email, e.getMessage(), e);
            return ApiResponse.error("检查邮箱失败");
        }
    }

    /**
     * 检查手机号是否存在
     * @param phone 手机号
     * @param excludeId 排除的用户ID（可选）
     * @return 是否存在
     */
    @GetMapping("/checkPhone/{phone}")
    @Operation(summary = "检查手机号是否存在", description = "检查手机号是否已被使用")
    public ApiResponse<Boolean> checkPhoneExists(
            @Parameter(description = "手机号", required = true)
            @PathVariable String phone,
            @Parameter(description = "排除的用户ID")
            @RequestParam(required = false) Long excludeId) {
        try {
            Boolean exists = merchantUserService.checkPhoneExists(phone, excludeId);
            return ApiResponse.success(exists);
        } catch (BusinessException e) {
            log.error("检查手机号失败: phone={}, error={}", phone, e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("检查手机号异常: phone={}, error={}", phone, e.getMessage(), e);
            return ApiResponse.error("检查手机号失败");
        }
    }








}